package com.ruoyi.web.controller.project;

import java.util.Date;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.AESECBPKCS5Util;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.project.domain.ConContract;
import com.ruoyi.project.domain.ConProcess;
import com.ruoyi.project.service.IConContractService;
import com.ruoyi.project.service.IConProcessService;

/**
 * 合同进度Controller
 * 
 * @author phil
 * @date 2020-06-02
 */
@Controller
@RequestMapping("/contract/process")
public class ConProcessController extends BaseController{
	private String prefix = "project/con_process";

	@Autowired
	private IConProcessService conProcessService;

	@Autowired
	private IConContractService conContractService;

	@RequiresPermissions("contract:process:view")
	@GetMapping()
	public String process(){
		return prefix + "/process";
	}

	/**
	 * 查询合同进度列表
	 */
	@RequiresPermissions("contract:process:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(ConProcess conProcess){
		startPage();
		List<ConProcess> list = conProcessService.selectConProcessList(conProcess);
		return getDataTable(list);
	}

	/**
	 * 导出合同进度列表
	 */
	@RequiresPermissions("contract:process:export")
	@Log(title = "合同进度", businessType = BusinessType.EXPORT)
	@PostMapping("/export")
	@ResponseBody
	public AjaxResult export(ConProcess conProcess){
		List<ConProcess> list = conProcessService.selectConProcessList(conProcess);
		ExcelUtil<ConProcess> util = new ExcelUtil<ConProcess>(ConProcess.class);
		return util.exportExcel(list, "process");
	}

	/**
	 * 下载导入模板
	 * 
	 * @return
	 */
	@RequiresPermissions("contract:process:importTemplate")
	@GetMapping("/importTemplate")
	@ResponseBody
	public AjaxResult importTemplate(){
		ExcelUtil<ConProcess> util = new ExcelUtil<ConProcess>(ConProcess.class);
		return util.importTemplateExcel("合同里程碑数据");
	}

	/**
	 * 合同里程碑导入
	 * 
	 * @param file
	 * @param updateSupport
	 * @return
	 * @throws Exception
	 */
	@RequiresPermissions("contract:process:import")
	@PostMapping("/importData")
	@ResponseBody
	public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception{
		ExcelUtil<ConProcess> util = new ExcelUtil<ConProcess>(ConProcess.class);
		List<ConProcess> conProcessList = util.importExcel(file.getInputStream());
		String message = importConProcess(conProcessList, updateSupport);
		return AjaxResult.success(message);
	}

	/**
	 * 导入合同里程碑
	 * 
	 * @param conProcessList
	 * @param isUpdateSupport
	 * @param operName
	 * @return
	 */
	public String importConProcess(List<ConProcess> conProcessList, boolean isUpdateSupport) throws Exception{
		if(StringUtils.isNull(conProcessList) || conProcessList.size() == 0){
			throw new BusinessException("导入数据不能为空！");
		}

		// 查询合同列表
		ConContract oldContract = new ConContract();
		List<ConContract> contractList = conContractService.selectConContractList(oldContract);

		int failureNum = 0;
		int rowNum = 1; // 起始行数
		StringBuilder successMsg = new StringBuilder();
		StringBuilder failureMsg = new StringBuilder();
		for(ConProcess conProcess : conProcessList){
			rowNum++;

			// 合同编号转换
			String contractNO = conProcess.getContractNO();
			if(StringUtils.isEmpty(contractNO)){
				failureNum++;
				failureMsg.append("<br/>" + failureNum + "、第" + rowNum + "行，合同编号不允许为空");
			}else{
				Long contractId = selectContractIdByNO(contractNO, contractList);
				if(contractId == null){
					failureNum++;
					failureMsg.append("<br/>" + failureNum + "、第" + rowNum + "行，合同编号在系统内不存在");
				}else{
					conProcess.setConId(contractId);
				}
			}

			// 里程碑编号
			String processNo = conProcess.getProcessNo();
			if(StringUtils.isEmpty(processNo)){
				failureNum++;
				failureMsg.append("<br/>" + failureNum + "、第" + rowNum + "行，里程碑编号不允许为空");
			}

			// 可催收比例
			Double collectibleRatio = conProcess.getCollectibleRatio();
			if(collectibleRatio == null){
				failureNum++;
				failureMsg.append("<br/>" + failureNum + "、第" + rowNum + "行，可催收比例不允许为空");
			}

			// 累计可催收比例
			Double collectibleRatioSum = conProcess.getCollectibleRatio();
			if(collectibleRatioSum == null){
				failureNum++;
				failureMsg.append("<br/>" + failureNum + "、第" + rowNum + "行，可催收比例不允许为空");
			}

			String processAmount = conProcess.getProcessAmount();
			if(StringUtils.isNotEmpty(processAmount)){
				conProcess.setProcessAmount(AESECBPKCS5Util.encrypt(processAmount));
			}

			String receivableAmount = conProcess.getReceivableAmount();
			if(StringUtils.isNotEmpty(receivableAmount)){
				conProcess.setReceivableAmount(AESECBPKCS5Util.encrypt(receivableAmount));
			}

			String receivingAmount = conProcess.getReceivingAmount();
			if(StringUtils.isNotEmpty(receivingAmount)){
				conProcess.setReceivingAmount(AESECBPKCS5Util.encrypt(receivingAmount));
			}

			conProcess.setCreateTime(new Date());
			conProcess.setCreateBy(ShiroUtils.getSysUser().getLoginName());
		}

		if(failureNum > 0){
			failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 处数据格式不正确，错误如下：");
			throw new BusinessException(failureMsg.toString());
		}else{
			// 插入项目数据
			int successNum = conProcessService.insertConProcessList(conProcessList, ShiroUtils.getSysUser().getLoginName(), ShiroUtils.getSysUser().getUserId());
			successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
		}
		return successMsg.toString();
	}

	/**
	 * 根据项目编码查询项目ID
	 * 
	 * @param contractNO
	 * @param contractList
	 * @return
	 */
	private Long selectContractIdByNO(String contractNO, List<ConContract> contractList){
		Long contractId = null;
		if(contractList != null && contractList.size() > 0 && contractNO != null && !"".equals(contractNO)){
			for(ConContract contract : contractList){
				if(contractNO.trim().equals(contract.getContractNo())){
					contractId = contract.getContractId();
					break;
				}
			}
		}
		return contractId;
	}

	/**
	 * 新增合同进度
	 */
	@GetMapping("/add")
	public String add(){
		return prefix + "/add";
	}

	/**
	 * 新增保存合同进度
	 */
	@RequiresPermissions("contract:process:add")
	@Log(title = "合同进度", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(ConProcess conProcess) throws Exception{
		String processAmount = conProcess.getProcessAmount();
		String receivableAmount = conProcess.getReceivableAmount();
		String receivingAmount = conProcess.getReceivingAmount();
		if(StringUtils.isNotEmpty(processAmount)){
			conProcess.setProcessAmount(AESECBPKCS5Util.encrypt(processAmount));
		}
		if(StringUtils.isNotEmpty(receivableAmount)){
			conProcess.setReceivableAmount(AESECBPKCS5Util.encrypt(receivableAmount));
		}
		if(StringUtils.isNotEmpty(receivingAmount)){
			conProcess.setReceivingAmount(AESECBPKCS5Util.encrypt(receivingAmount));
		}
		return toAjax(conProcessService.insertConProcess(conProcess));
	}

	/**
	 * 修改合同进度
	 */
	@GetMapping("/edit/{processId}")
	public String edit(@PathVariable("processId") Long processId, ModelMap mmap){
		ConProcess conProcess = conProcessService.selectConProcessById(processId);
		mmap.put("conProcess", conProcess);
		return prefix + "/edit";
	}

	/**
	 * 修改保存合同进度
	 */
	@RequiresPermissions("contract:process:edit")
	@Log(title = "合同进度", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(ConProcess conProcess){
		return toAjax(conProcessService.updateConProcess(conProcess));
	}

	/**
	 * 删除合同进度
	 */
	@RequiresPermissions("contract:process:remove")
	@Log(title = "合同进度", businessType = BusinessType.DELETE)
	@PostMapping("/remove")
	@ResponseBody
	public AjaxResult remove(String ids){
		return toAjax(conProcessService.deleteConProcessByIds(ids));
	}
}
